<?php

$act = isset($_REQUEST['act'])? $_REQUEST['act'] : 'view';

/* Hiển thị danh sách mail đã gửi */
if ($act == 'view') {
	$sent_mails = array();

	// Lấy mail đã gửi
	$sql = "SELECT sent_mail_id, subject, message, DATE_FORMAT(sent_date, '%H:%i:%s %d-%m-%Y') as sent_date  FROM sent_mail";
	$result = mysql_query($sql);
	while ($row = mysql_fetch_assoc($result)) {
		$sent_mails[] = $row;
		$count = count($sent_mails);
		$sent_mails[$count - 1]['receiver'] = getReceivedContact($sent_mails[$count - 1]['sent_mail_id']);
	}

	/* Thông báo */
	if (isset($_SESSION['send_success'])) {
		if ($_SESSION['send_success']) {
			$success = true;
			$msg = 'Đã gửi thành công!';
		}

		unset($_SESSION['send_success']);
	}
	if (isset($_SESSION['success'])) {
		$success = true;
		$msg = $_SESSION['msg'];
		unset($_SESSION['success']);
	}

	/* Load template */
	if (file_exists(DIR_TPL . 'mail/sent_mail.tpl.php')) {
		include(DIR_TPL . 'mail/sent_mail.tpl.php');
	} else {
		_log('Could not load the template "mail/sent_mail"!', true);
	}
}

/* Xóa nhiều mail */
elseif ($act == 'delete') {
	$sent_mails = $_REQUEST['sent_mails'];

	$sql = "DELETE FROM sent_mail WHERE sent_mail_id IN (%s)";
	$sql2 = "DELETE FROM sent_mail_to_contact WHERE sent_mail_id IN (%s)";
	$q = sprintf($sql, implode(',', $sent_mails));
	$q2 = sprintf($sql2, implode(',', $sent_mails));

	mysql_query($q) OR _log('Error query: ' . $q);
	mysql_query($q2) OR _log('Error query: ' . $q2);

	$_SESSION['success'] = true;
	$_SESSION['msg'] = 'Đã xóa mail!';

	session_write_close();
	header('Location: ' . URL . '?page=mail_da_gui');
}